package com.guiji.quartz.domain;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.config.ProxyConfig;
import com.guiji.quartz.task.DataSaveUtil;
import com.guiji.quartz.util.DelPicUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description: 需要代理
 * @author: wangxw
 * @date 2021/11/24 14:51
 */
public class Bnnbloomberg {
	private static final Logger log = LoggerFactory.getLogger(Bnnbloomberg.class);

	public static void mainMethod() throws Exception {
		List<String> list = new ArrayList<>();
		list.add("https://www.bnnbloomberg.ca/commodities");
		list.add("https://www.bnnbloomberg.ca/economics");
		list.add("https://www.bnnbloomberg.ca/investing");
		list.forEach(url -> {
			HttpResponse response = null;
			try {
				response = HttpRequest.get(url)
					.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
					.header("Accept-Encoding", "gzip, deflate")
					.setConnectionTimeout(30000)
					.execute();

			} catch (Exception e) {
				log.error("访问 https://www.bnnbloomberg.ca/commodities 失败" + e);
				return;
			}
			String category = "Bnnbloomberg-CommoditiesNews";
			if (url.contains("economics")) {
				category = "bnnbloomberg-Economy";
			}
			if (url.contains("investing")) {
				category = "bnnbloomberg-Investing";
			}
			if (null != response && response.getStatus() == 200) {
				List<HttpCookie> cookies = response.getCookies();
				String resp = response.body();
				Set<String> resUrl = getUrl(resp);
				try {
					getContent(resUrl, cookies,category);
				} catch (Exception e) {
				}
			} else {
				log.error("https://www.bnnbloomberg.ca/commodities " + String.valueOf(response.getStatus()));
			}
		});

	}

	private static void getContent(Set<String> listContent, List<HttpCookie> cookies,String category) throws MalformedURLException, URISyntaxException, InterruptedException {
		for (String url : listContent) {
			Thread.sleep(1000);
			if (!url.startsWith("https")) {
				url = new StringBuffer("https://www.bnnbloomberg.ca/commodities").append(url).toString();
			}
			if (null != cookies && cookies.size() > 0) {
				CookieManager ccm = new CookieManager();
				CookieStore CookieStore = ccm.getCookieStore();
				for (HttpCookie cookie : cookies) {
					URL domain = new URL("https://www.bnnbloomberg.ca");
					CookieStore.add(domain.toURI(), cookie);
				}
				HttpRequest.setCookieManager(ccm);
			}

			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = HttpRequest.get(url).setConnectionTimeout(15000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}
			String title = null;
			try {
				title = (String) jxDocument.sel("//div[@class='article']//h1//text()").get(0);
			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			StringBuffer content = new StringBuffer();
			String contentStr = null;
			JXDocument jxDocumentP;
			try {

				Document document = Jsoup.parse(doc);
				Element mainArea = document.getElementsByClass("article-text").get(0);
				Elements pElements = mainArea.select("P");
				if (null != pElements && pElements.size() > 0) {
					for (Element pdom : pElements) {
						jxDocumentP = new JXDocument(pdom.toString());
						String temp = jxDocumentP.sel("//text()").get(0).toString();
						if (null != temp) {
							content.append(temp + "$$$");
						}
					}
				}

				contentStr = content.toString();
			} catch (Exception e) {
				continue;
			}

			Set<String> newImgs = new HashSet<>();
			String img = null;
			try {
				int imgSize = jxDocument.sel("//div[@class='article-text']//img/@src").size();
				if (imgSize > 0) {
					String temp = null;
					for (int k = 0; k < imgSize; k++) {
						temp = jxDocument.sel("//div[@class='article-text']//img/@src").get(k).toString();
						img = temp.strip();
						if(null!=img && !img.isEmpty()){
							if(!img.startsWith("http")){
								img = new StringBuffer("https://www.bnnbloomberg.ca").append(img).toString();
								newImgs.add(img);
							}
						}

					}
				}
				imgSize = jxDocument.sel("//div[@class='article-image']//img/@src").size();
				if (imgSize > 0) {
					String temp = null;
					for (int k = 0; k < imgSize; k++) {
						temp = jxDocument.sel("//div[@class='article-image']//img/@src").get(k).toString();
						img = temp.strip();
						if(null!=img && !img.isEmpty()){
							if(!img.startsWith("http")){
								img = new StringBuffer("https://www.bnnbloomberg.ca").append(img).toString();
								newImgs.add(img);
							}
						}

					}
				}

			} catch (Exception e) {
				log.error("可能没有图片");
				img = "";
			}

			Date date = new Date();
			if (contentStr.length() > 50000 || contentStr.replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				System.out.println("=======================================================");
				System.out.println(url);
				System.out.println(title);

				for (String imgitem : newImgs) {
					System.out.println(" " + imgitem);
				}
				System.out.println(contentStr);
				System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
				DataSaveUtil.saveData(title, contentStr, newImgs, url, date, "https://www.bnnbloomberg.ca/commodities||", category);
				log.info(Thread.currentThread().getName() + "-----------------{}----------------",category);
			} catch (Exception e) {
				continue;
			}

		}
	}

	private static Set<String> getUrl(String content) {
		Set<String> res = new HashSet<>();
		Document document = Jsoup.parse(content);
		Element mainArea = document.getElementsByClass("content-main").get(0);
		Elements aElements = mainArea.select("a");
		String url = null;
		if (null != aElements && aElements.size() > 0) {
			for (Element adom : aElements) {
				url = adom.attr("href");
				if (url != null && !url.isEmpty() && url.startsWith("/")) {
					res.add(url);
				}
			}

		}

		return res;
	}

//	public static void main(String[] args) throws Exception {
//		mainMethod();
//	}


}


